package com.cjkj.common.security.service;

import com.cjkj.common.core.constant.CacheConstants;
import com.cjkj.common.core.constant.SecurityConstants;
import com.cjkj.common.core.utils.JwtUtils;
import com.cjkj.common.core.utils.StringUtils;
import com.cjkj.common.core.utils.uuid.IdUtils;
import com.cjkj.common.redis.service.RedisService;
import com.cjkj.common.security.utils.SecurityUtils;
import com.cjkj.system.api.model.AppletLoginUser;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 小程序Token工具类
 */
@Component
public class AppletTokenService {

    @Resource
    private RedisService redisService;
    private final static String ACCESS_TOKEN = CacheConstants.WX_LOGIN_TOKEN_KEY;
    private final static long EXPIRE_TIME = CacheConstants.APP_EXPIRATION;

    /**
     * 创建令牌
     */
    public Map<String,Object> createToken(AppletLoginUser loginUser){
        String token = IdUtils.fastUUID();
        String openId = loginUser.getOpenid();
        String userName = loginUser.getNickName();
        loginUser.setToken(token);
        refreshToken(loginUser);

        // Jwt存储信息
        Map<String,Object> claimsMap = new HashMap<>();
        claimsMap.put(SecurityConstants.APP_USER_KEY, token);
        claimsMap.put(SecurityConstants.APP_USER_ID, loginUser.getAccountId());
        claimsMap.put(SecurityConstants.APP_USER_NAME, userName);
        claimsMap.put(SecurityConstants.APP_OPEN_ID, openId);

        //接口返回信息
        Map<String,Object> rspMap = new HashMap<>();
        rspMap.put("doctorAccount", loginUser.getDoctor());
        rspMap.put("access_token", JwtUtils.createToken(claimsMap, CacheConstants.JWT_EXPIRATION));
        return rspMap;
    }

    /**
     * 获取用户身份信息
     */
    public AppletLoginUser getLogUser(HttpServletRequest request){
        String token = SecurityUtils.getToken(request);
        return getLogUser(token);
    }

    /**
     * 获取用户身份信息
     */
    public AppletLoginUser getLogUser(String token){
        try {
            if(StringUtils.isNotEmpty(token)){
                String userKey = JwtUtils.getAppUserKey(token);
                return redisService.getCacheObject(getTokenKey(userKey));
            }
        }catch (Exception e){
            System.err.println(e.getMessage());
        }
        return null;
    }
    /**
     * 删除用户缓存信息
     */
    public void delLoginUser(String token){
        if(StringUtils.isNotEmpty(token)){
            String userKey = JwtUtils.getAppUserKey(token);
            redisService.deleteObject(getTokenKey(userKey));
        }
    }

    public void refreshToken(AppletLoginUser loginUser){
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, EXPIRE_TIME, TimeUnit.MILLISECONDS);
    }

    private String getTokenKey(String token)
    {
        return ACCESS_TOKEN + token;
    }

    /**
     * 设置用户医生账号缓存
     * @param doctorAccount 医生账号
     */
    public void setUserDoctorAccountCache(HttpServletRequest request, String doctorAccount){
        AppletLoginUser logUser = getLogUser(request);
        logUser.setDoctor(doctorAccount);
        refreshToken(logUser);
    }
}